package ly.count.ohos.sdk;


import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.sysappcomponents.settings.SystemSettings;

import java.util.UUID;

public class OpenUDIDAdapter {
    public final static String PREF_KEY = "openudid";
    public final static String PREFS_NAME = "openudid_prefs";
    public static DatabaseHelper databaseHelper;

    public static String OpenUDID = null;

    public static void sync(final Context context) {
        if (OpenUDID != null){
            return;
        }
        //Try to get the openudid from local preferences
        OpenUDID = getDatabaseHelper(context).getPreferences(PREFS_NAME).getString(PREF_KEY, null);
        if (OpenUDID == null) //Not found
        {
            generateOpenUDID(context);
            storeOpenUDID(context);//Store it locally
        }

        Countly.sharedInstance().L.d("[OpenUDID] ID: " + OpenUDID);
    }

    /*
     * Generate a new OpenUDID
     */
    private static void generateOpenUDID(Context context) {
        Countly.sharedInstance().L.d("[OpenUDID] Generating openUDID");

        if (OpenUDID == null || OpenUDID.equals("9774d56d682e549c") || OpenUDID.length() < 15) {
            OpenUDID = UUID.randomUUID().toString();
        }
    }

    public static String getOpenUDID() {
        return OpenUDID;
    }

    private static void storeOpenUDID(Context context) {
        getDatabaseHelper(context).getPreferences(PREFS_NAME).putString(PREF_KEY, OpenUDID).flush();
    }

    private static DatabaseHelper getDatabaseHelper(Context context){
        if(databaseHelper == null){
            databaseHelper = new DatabaseHelper(context);
        }
        return databaseHelper;
    }
}
